package com.mall.shopping.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.shopping.ICartDeleteService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Description:
 * @Author: WD created on 2021-09-29 15:42
 * @Version:
 */


@Slf4j
@Component
@Service
public class CartDeleteServiceImpl implements ICartDeleteService {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;



    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();

        try {
            request.requestCheck();

            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            //数据库删除
            Map<Object, Object> map = redissonClient.getMap(generatorCartItemKey(userId));
            CartProductDto productDto = JSON.parseObject((String) map.get(itemId), CartProductDto.class);
            map.remove(itemId);

            //商品返还
            //商品表
            Item item = itemMapper.selectByPrimaryKey(itemId);
            Integer num = item.getNum();
            num= Math.toIntExact(productDto.getProductNum() + num);
            item.setNum(num);
            int i = itemMapper.updateByPrimaryKey(item);
            //库存表



            //成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }


        return response;

    }



    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();

            Long userId = request.getUserId();
            Map<Object, Object> map = redissonClient.getMap(generatorCartItemKey(userId));
            ArrayList<CartProductDto> dtoList = new ArrayList<>();
            Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<Object, Object> entry = iterator.next();
                CartProductDto productDto = JSON.parseObject((String) entry.getValue(), CartProductDto.class);
                if ("true".equals(productDto.getChecked())) {
                    dtoList.add(productDto);
                    iterator.remove();
                }
            }

            //返还商品
            for (CartProductDto productDto : dtoList) {
                Long itemId = productDto.getProductId();
                Item item = itemMapper.selectByPrimaryKey(itemId);
                Integer num = item.getNum();
                num= Math.toIntExact(productDto.getProductNum() + num);
                item.setNum(num);
                int i = itemMapper.updateByPrimaryKey(item);
            }
            //成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }



    private String generatorCartItemKey(long userId) {
        StringBuilder sb = new StringBuilder(GlobalConstants.CART_ITEM_CACHE_PREFIX);
        sb.append(":").append(userId);
        return sb.toString();
    }
}
